<template>
  <div>
    <div style="height:6vh;background-color:#fff;padding: 10px 20px;">
      <span style="line-height: 60px;font-size: 20px;">薪资管理</span>
      <el-button
          type="primary"
          v-if="getUser.level >= 20"
          style="float: right; margin-top: 13px;"
          @click="beforeAddSalary">
        新增薪资记录
      </el-button>
    </div>

    <!-- 薪资记录弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" :before-close="handleClose">
      <el-form label-width="100px" :model="salaryForm" :rules="rules" ref="salaryForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="员工" prop="employeeId">
              <el-select
                  v-model="salaryForm.employeeId"
                  placeholder="请选择员工"
                  filterable
                  style="width:100%">
                <el-option
                    v-for="emp in employeeOptions"
                    :key="emp.id"
                    :label="emp.name"
                    :value="emp.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应发月份" prop="month">
              <el-date-picker
                  v-model="salaryForm.month"
                  type="month"
                  placeholder="选择月份"
                  value-format="yyyy-MM"
                  style="width:100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应工作天数" prop="workDays">
              <el-input-number
                  v-model="salaryForm.workDays"
                  :min="0"
                  style="width:100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基本工资" prop="baseSalary">
              <el-input-number
                  v-model="salaryForm.baseSalary"
                  :precision="2"
                  :min="0"
                  style="width:100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="补贴" prop="allowance">
              <el-input-number
                  v-model="salaryForm.allowance"
                  :precision="2"
                  :min="0"
                  style="width:100%"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扣款" prop="deduction">
              <el-input-number
                  v-model="salaryForm.deduction"
                  :precision="2"
                  :min="0"
                  style="width:100%"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="扣款原因" prop="reasons" v-if="salaryForm.deduction!==0">
          <el-input v-model="salaryForm.reasons"
                    placeholder="请输入扣款原因"
                    style="width:100%"
                    type="textarea"
                    :rows="3">
          </el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发放状态" prop="status">
              <el-select v-model="salaryForm.status" placeholder="请选择状态" style="width:100%">
                <el-option label="已发放" :value="1"></el-option>
                <el-option label="未发放" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发放日期" prop="paymentDate" v-if="salaryForm.status === 1">
              <el-date-picker
                  v-model="salaryForm.paymentDate"
                  type="date"
                  placeholder="选择发放日期"
                  value-format="yyyy-MM-dd"
                  style="width:100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 搜索区域 -->
    <el-card style="margin: 20px;height: 70px;">
      <el-form :inline="true" @submit.native.prevent>
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.employeeName" @change="loadData"></el-input>
        </el-form-item>
        <el-form-item label="月份范围">
          <el-date-picker
              v-model="searchForm.monthRange"
              type="monthrange"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
              value-format="yyyy-MM"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadData">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card style="margin: 20px;">
      <el-table :data="salaryList">
        <el-table-column label="编号" type="index" width="80" align="center"></el-table-column>
        <el-table-column label="员工姓名" prop="name" align="center"></el-table-column>
        <el-table-column label="考勤天数" prop="attendanceDays" align="center"></el-table-column>
        <el-table-column label="应工作天数" prop="workDays" align="center"></el-table-column>
        <el-table-column label="应发月份" prop="month" align="center"></el-table-column>
        <el-table-column label="基本工资" prop="baseSalary" align="center"></el-table-column>
        <el-table-column label="绩效工资" prop="performancePay" align="center"></el-table-column>
        <el-table-column label="补贴" prop="allowance" align="center"></el-table-column>
        <el-table-column label="扣款" prop="deduction" align="center"></el-table-column>
        <el-table-column label="扣款原因" align="center" show-overflow-tooltip>
          <template #default="{row}">{{ row.reasons ? row.reasons : '无' }}</template>
        </el-table-column>
        <el-table-column label="实发工资" prop="totalAmount" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{row}">{{ formatStatus(row.status) }}</template>
        </el-table-column>
        <el-table-column label="发放日期" prop="paymentDate" align="center"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template #default="scope">
            <el-button link type="text" @click="editSalary(scope.row)">编辑</el-button>
            <el-button link type="text" @click="deleteSalary(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.current"
          :page-sizes="[3, 4, 5]"
          :page-size="pagination.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          style="margin-top: 20px;"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios'
import { Message } from 'element-ui'
import qs from "qs";

export default {
  data() {
    return {
      getUser: this.$getUser(),
      dialogVisible: false,
      dialogTitle: '新增薪资记录',
      salaryForm: {
        id: null,
        employeeId: null,
        month: null,
        workDays: 0,
        baseSalary: 0,
        allowance: 0,
        deduction: 0,
        reasons: '',
        status: 1,
        paymentDate: null
      },
      rules: {
        employeeId: [{ required: true, message: '请选择员工', trigger: 'blur' }],
        month: [{ required: true, message: '请选择月份', trigger: 'change' }],
        baseSalary: [{ required: true, message: '请输入基本工资', trigger: 'blur' }],
        workDays: [{ required: true, message: '请输入天数', trigger: 'blur' }],
        status: [{ required: true, message: '请选择发放状态', trigger: 'blur' }]
      },
      searchForm: {
        employeeName: '',
        monthRange: []
      },
      salaryList: [],
      employeeOptions: [],
      pagination: {
        current: 1,
        size: 3,
        total: 0
      }
    }
  },
  mounted() {
    this.loadData()
    this.loadEmployees()
  },
  methods: {
    // 加载薪资数据
    loadData() {
      let data = qs.stringify({
        pageCurrent: this.pagination.current,
        pageSize: this.pagination.size,
        employeeName: this.searchForm.employeeName,
        startMonth: this.searchForm.monthRange?.[0],
        endMonth: this.searchForm.monthRange?.[1]
      });

      axios.get(this.$BASE_URL + '/v1/salary/list?'+data)
          .then(res => {
            if (res.data.state === 2000) {
              console.log(res.data);
              this.salaryList = res.data.data.salaryList;
              this.pagination.total = res.data.data.total;
            } else {
              Message.error(res.data.message)
            }
          })
    },

    // 加载员工列表
    loadEmployees() {
      axios.get(this.$BASE_URL + '/v1/user/list')
          .then(res => {
            if (res.data.state === 2000) {
              this.employeeOptions = res.data.data.userList;
            }
          })
    },

    // 格式化状态显示
    formatStatus(status) {
      return status === 1 ? '已发放' : '未发放'
    },

    beforeAddSalary() {
      this.dialogTitle = '新增薪资记录'
      this.dialogVisible = true
    },

    editSalary(row) {
      this.dialogTitle = '编辑薪资记录'
      this.salaryForm = {
        ...row,
        // 保持数据类型一致
        baseSalary: parseFloat(row.baseSalary),
        allowance: parseFloat(row.allowance),
        deduction: parseFloat(row.deduction)
      }
      this.dialogVisible = true
    },

    deleteSalary(id) {
      this.$confirm('确定删除该记录吗？', '提示', {type: 'warning'})
          .then(() => {
            axios.post(this.$BASE_URL + `/v1/salary/delete/${id}`)
                .then(res => {
                  if (res.data.state === 2000) {
                    Message.success('删除成功')
                    this.loadData()
                  } else {
                    Message.error(res.data.message)
                  }
                })
          })
          .catch(() => {})
    },

    submit() {
      this.$refs.salaryForm.validate(valid => {
        if (valid) {
          axios.post(this.$BASE_URL +'/v1/salary/save', qs.stringify(this.salaryForm))
              .then(res => {
                if (res.data.state === 2000) {
                  Message.success('操作成功')
                  this.handleClose()
                  this.loadData()
                } else {
                  Message.error(res.data.message)
                }
              })
        }
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.$refs.salaryForm.resetFields()
      this.salaryForm = {
        id: null,
        employeeId: null,
        month: null,
        workDays: 0,
        baseSalary: 0,
        allowance: 0,
        deduction: 0,
        reasons: '',
        status: 2,
        paymentDate: null
      }
    },

    resetSearch() {
      this.searchForm = {
        employeeName: '',
        monthRange: []
      }
      this.pagination.current = 1
      this.loadData()
    },

    handleSizeChange(size) {
      this.pagination.size = size
      this.loadData()
    },

    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadData()
    }
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.el-card {
  margin: 20px;
}

.el-form--inline .el-form-item {
  margin-bottom: 0;
}
</style>